﻿using System;
using System.IO;

namespace ETModel
{
    public class OuterHeader : IMHeader
    {
        private byte[] opByte = new byte[2];
        public int ID
        {
            get;
            set;
        }

        public ushort Opcode
        {
            get;
            set;
        }

        public ushort ChildOpcode
        {
            get;
            set;
        }

        public byte ErrorCode
        {
            get;
            set;
        }

        public byte RpcId
        {
            get;
            set;
        }

        public void Clear()
        {
            ID = 0;
            Opcode = 0;
            ChildOpcode = 0;
            ErrorCode = 0;
            RpcId = 0;
        }

        public void Deserialize(MemoryStream stream)
        {
            stream.Read(opByte, 0, opByte.Length);
            Array.Reverse(opByte);
            Opcode = BitConverter.ToUInt16(opByte, 0);

            stream.Read(opByte, 0, opByte.Length);
            Array.Reverse(opByte);
            ChildOpcode = BitConverter.ToUInt16(opByte, 0);

            stream.Read(opByte, 0, sizeof(ushort));
            ErrorCode = opByte[0];
            RpcId = opByte[1];

            ID = (ChildOpcode << 0x10) | Opcode;

        }

        public void Serialize(MemoryStream stream)
        {
            Opcode = (ushort)(ID & 0xFFFF);
            ChildOpcode = (ushort)(ID >> 0x10);
            ErrorCode = 0;
            if(RpcId == 0) RpcId = RpcIdGenerater.GenerateId();

            byte[] bytes = BitConverter.GetBytes(Opcode);
            Array.Reverse(bytes);
            stream.Write(bytes, 0, bytes.Length);
            bytes = BitConverter.GetBytes(ChildOpcode);
            Array.Reverse(bytes);
            stream.Write(bytes, 0, bytes.Length);
            stream.WriteByte(ErrorCode);
            stream.WriteByte(RpcId);
        }
    }
}
